'use strict';

const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
    const {
        typeDesc = '电影',
        cat = '',
        area = '',
        dir = '',
        year = 2024,
        num = 20,
        page = 1
    } = event;

    try {
        // 构建查询条件对象
        const queryConditions = {};

        // 添加 typeDesc 查询条件
        if (typeDesc !== "") {
            queryConditions.typeDesc = new RegExp(typeDesc, 'i');
        }

        // 添加 cat 查询条件
        if (cat !== "") {
            queryConditions.cat = new RegExp(cat, 'i');
        }

        // 添加 area 查询条件
        if (area !== "") {
            queryConditions.area = new RegExp(area, 'i');
        }

        // 添加 dir 查询条件
        if (dir !== "") {
            queryConditions.dir = new RegExp(dir, 'i');
        }

        // 添加 year 查询条件
        if (year !== "") {
            queryConditions.year = parseInt(year);
        }

        // 执行查询
        const dataResult = await db.collection('movies')
            .orderBy('movieId', 'desc')
            .where(queryConditions)
            .skip(num * (page - 1)) // 修正分页偏移
            .limit(num)
            .get();

        return {
            code: 200,
            message: '获取列表成功',
            data: dataResult.data
        };
    } catch (e) {
        return {
            code: 400,
            message: e.message
        };
    }
};
